package info.leetcode.answer.Array.TwoDimensionalArray.change;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 重塑矩阵
 * @date 2024/2/27 9:18
 */
public class MatrixReshape {
    public static void main(String[] args) {
        int[][] mat = {{1, 2}, {3, 4}};
        int r = 2;
        int c = 2;
        int[][] result = matrixReshape(mat, r, c);
        System.out.println(result);
    }

    private static int[][] matrixReshape(int[][] mat, int r, int c) {
        if (mat.length * mat[0].length != r * c) {
            return mat;
        }
        int[][] result = new int[r][c];
        // 横坐标
        int transverseIndex = 0;
        // 纵坐标
        int directionIndex = 0;

        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j++) {
                if (directionIndex == c) {
                    directionIndex = 0;
                    transverseIndex++;
                }
                if (transverseIndex == r) {
                    return mat;
                }
                result[transverseIndex][directionIndex] = mat[i][j];
                directionIndex++;
            }
        }

        return result;
    }
}
